import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Tree, Button, Divider, Table, Input } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { getPathByKey } from '@/utils/utils';

import styles from './TypeList.less';

const { TreeNode } = Tree;
const { Search } = Input;

const generateDataList = tree => {
  const dataList = [];
  const generateList = data => {
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList(node.children, node.key);
      }
    }
  };
  generateList(tree);
  return dataList;
};

const getParentKey = (key, tree) => {
  let parentKey;
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

const getSelfAndChildren = (key, tree) => {
  const data = [];
  const paths = getPathByKey(key, 'key', tree);
  if (paths && paths.length) {
    const { children, ...others } = paths[paths.length - 1];
    data.push(others);
    if (children && children.length) {
      data.push(...children);
    }
  }
  return data;
};

const showTotal = total => `${total} 条类型`;

@connect(
  ({ devicetype, loading }) => ({
    tree: devicetype.tree,
    loading: loading.effects['devicetype/fetchTree'],
  }),
  dispatch => ({
    fetchTree: args =>
      dispatch({
        type: 'devicetype/fetchTree',
        payload: args,
      }),
  })
)
class DeviceTypeList extends PureComponent {
  state = {
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,
    selectedKey: '',
  };

  columns = [
    {
      title: '设备类型编码',
      dataIndex: 'key',
    },
    {
      title: '设备类型名称',
      dataIndex: 'title',
    },
    {
      title: '设备类型描述',
      dataIndex: 'description',
    },
    {
      title: '操作',
      render: record => (
        <Fragment>
          <a onClick={() => console.log(record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => console.log(record)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { fetchTree } = this.props;
    fetchTree();
  }

  onSelect = selectedKeys => {
    if (selectedKeys && selectedKeys.length) {
      this.setState({
        selectedKey: selectedKeys[0],
      });
    }
  };

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onChange = e => {
    const { value } = e.target;
    const { tree } = this.props;
    const expandedKeys = this.dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, tree);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  };

  get dataList() {
    const { tree } = this.props;
    return generateDataList(tree);
  }

  get selectedData() {
    const { selectedKey } = this.state;
    const { tree } = this.props;
    return getSelfAndChildren(selectedKey, tree);
  }

  render() {
    const { searchValue, expandedKeys, autoExpandParent } = this.state;
    const { tree = [] } = this.props;

    const content = (
      <div className={styles.pageHeaderContent}>
        <Search
          className={styles.contentSearch}
          style={{ marginBottom: 8 }}
          placeholder="设备类型名称"
          onChange={this.onChange}
        />
      </div>
    );

    const extraContent = (
      <div className={styles.extraBtn}>
        <Button icon="plus" type="primary">
          新建
        </Button>
      </div>
    );

    const loop = data =>
      data.map(item => {
        const index = item.title.indexOf(searchValue);
        const beforeStr = item.title.substr(0, index);
        const afterStr = item.title.substr(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span style={{ color: '#f50' }}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{item.title}</span>
          );
        if (item.children) {
          return (
            <TreeNode key={item.key} title={title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={title} />;
      });

    return (
      <PageHeaderWrapper title="设备类型" content={content} extraContent={extraContent}>
        <GridContent className={styles.typeList}>
          <Row gutter={24}>
            <Col lg={6} md={24}>
              <Card bordered={false} style={{ marginBottom: 24 }}>
                <Tree
                  showLine
                  onExpand={this.onExpand}
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent}
                  onSelect={this.onSelect}
                >
                  {loop(tree)}
                </Tree>
              </Card>
            </Col>
            <Col lg={18} md={24}>
              <Card bordered={false}>
                <Table
                  dataSource={this.selectedData}
                  columns={this.columns}
                  pagination={{ size: 'small', total: this.selectedData.length, showTotal }}
                />
              </Card>
            </Col>
          </Row>
        </GridContent>
      </PageHeaderWrapper>
    );
  }
}

export default DeviceTypeList;
